#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <termios.h>
#include "VehicleManager.h"

// 替代conio.h的跨平台实现
char getch() {
    char buf = 0;
    struct termios old = {0};
    if (tcgetattr(0, &old) < 0)
        perror("tcsetattr()");
    old.c_lflag &= ~ICANON;
    old.c_lflag &= ~ECHO;
    old.c_cc[VMIN] = 1;
    old.c_cc[VTIME] = 0;
    if (tcsetattr(0, TCSANOW, &old) < 0)
        perror("tcsetattr ICANON");
    if (read(0, &buf, 1) < 0)
        perror("read()");
    old.c_lflag |= ICANON;
    old.c_lflag |= ECHO;
    if (tcsetattr(0, TCSADRAIN, &old) < 0)
        perror("tcsetattr ~ICANON");
    return (buf);
}

int main() {
    VehicleManager manager;
    
    // 初始化10台小车
    std::cout << "正在初始化智能小车..." << std::endl;
    manager.initializeVehicles();
    
    // 将小车分配给学生
    std::cout << "正在将小车分配给学生..." << std::endl;
    manager.assignVehiclesToStudents();
    
    // 保存到文件
    std::cout << "正在保存小车信息到文件..." << std::endl;
    manager.saveToFile("vehicles.txt");
    std::cout << "小车信息已保存到 vehicles.txt 文件中。" << std::endl;
    
    // 从文件加载信息
    std::cout << "正在从文件加载小车信息..." << std::endl;
    manager.loadFromFile("vehicles.txt");
    
    // 显示小车信息
    std::cout << "\n智能小车信息查看系统" << std::endl;
    std::cout << "按 'n' 键查看下一辆小车" << std::endl;
    std::cout << "按 'p' 键查看上一辆小车" << std::endl;
    std::cout << "按 'q' 键退出程序" << std::endl;
    std::cout << "\n开始显示第一辆小车信息：" << std::endl;
    
    int currentIndex = 0;
    manager.displayVehicle(currentIndex);
    
    char key;
    while ((key = getch()) != 'q') {
        if (key == 'n') {
            // 下一辆小车
            if (currentIndex < (int)manager.getVehicleCount() - 1) {
                currentIndex++;
                manager.displayVehicle(currentIndex);
            } else {
                std::cout << "已经是最后一辆小车了！" << std::endl;
            }
        } else if (key == 'p') {
            // 上一辆小车
            if (currentIndex > 0) {
                currentIndex--;
                manager.displayVehicle(currentIndex);
            } else {
                std::cout << "已经是第一辆小车了！" << std::endl;
            }
        }
    }
    
    std::cout << "程序已退出。" << std::endl;
    return 0;
}